<template>
  <div class="user-works">
    <el-card>
      <div slot="header" class="clearfix">
        <span>我的作品</span>
        <el-button 
          style="float: right; padding: 3px 0" 
          type="text" 
          icon="el-icon-plus"
          @click="$router.push('/upload')">
          发布新作品
        </el-button>
      </div>
      
      <div class="empty-block" v-if="worksList.length === 0">
        <el-empty description="暂无作品，快去发布你的第一个作品吧！">
          <el-button type="primary" @click="$router.push('/upload')">发布作品</el-button>
        </el-empty>
      </div>
      
      <div v-else class="works-list">
        <el-table
          v-loading="loading"
          :data="worksList"
          stripe
          style="width: 100%">
          <el-table-column
            label="预览图"
            width="120"
            align="center">
            <template slot-scope="scope">
              <el-image 
                :src="scope.row.imgUrl" 
                style="width: 80px; height: 80px; border-radius: 4px"
                fit="cover"
                :preview-src-list="[scope.row.imgUrl]">
                <div slot="error" class="image-error">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column
            prop="title"
            label="标题"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="categoryName"
            label="分类"
            width="100">
          </el-table-column>
          <el-table-column
            label="状态"
            width="100">
            <template slot-scope="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="发布时间"
            width="180">
            <template slot-scope="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="250">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="viewDetail(scope.row.id)">查看</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="editWork(scope.row.id)"
                :disabled="scope.row.status === 2">编辑</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                class="delete-btn"
                @click="deleteWork(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="pagination" v-if="total > 0">
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page.sync="currentPage"
            :page-size="pageSize"
            layout="total, prev, pager, next"
            :total="total">
          </el-pagination>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  name: 'UserWorks',
  data() {
    return {
      worksList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      loading: false
    }
  },
  computed: {
    ...mapGetters(['userId'])
  },
  created() {
    this.fetchUserWorks()
  },
  methods: {
    async fetchUserWorks() {
      this.loading = true
      try {
        const params = {
          page: this.currentPage,
          pageSize: this.pageSize,
          userId: this.userId
        }
        const res = await this.$http.get('/photos/user', { params })
        if (res.data.code === 1) {
          this.worksList = res.data.data.records
          this.total = res.data.data.total
        } else {
          this.$message.error('获取作品列表失败')
        }
      } catch (error) {
        console.error('获取作品列表失败', error)
        this.$message.error('获取作品列表失败')
      } finally {
        this.loading = false
      }
    },
    handleCurrentChange(page) {
      this.currentPage = page
      this.fetchUserWorks()
    },
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hour = date.getHours().toString().padStart(2, '0')
      const minute = date.getMinutes().toString().padStart(2, '0')
      return `${year}-${month}-${day} ${hour}:${minute}`
    },
    getStatusType(status) {
      const statusMap = {
        0: 'info',    // 审核中
        1: 'success', // 已发布
        2: 'danger',  // 已拒绝
        3: 'warning'  // 已下架
      }
      return statusMap[status] || 'info'
    },
    getStatusText(status) {
      const statusMap = {
        0: '审核中',
        1: '已发布',
        2: '已拒绝',
        3: '已下架'
      }
      return statusMap[status] || '未知'
    },
    viewDetail(id) {
      this.$router.push(`/detail/${id}`)
    },
    editWork(id) {
      this.$router.push(`/edit/${id}`)
    },
    async deleteWork(work) {
      try {
        await this.$confirm('此操作将永久删除该作品, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const res = await this.$http.delete(`/photos/${work.id}`)
        if (res.data.code === 1) {
          this.$message.success('删除成功')
          this.fetchUserWorks()
        } else {
          this.$message.error(res.data.msg || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除作品失败', error)
          this.$message.error('删除失败')
        }
      }
    }
  }
}
</script>

<style scoped>
.empty-block {
  margin: 40px 0;
}

.works-list {
  margin-top: 20px;
}

.image-error {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.delete-btn {
  color: #F56C6C;
}

.delete-btn:hover {
  color: #f78989;
}
</style> 